package com.hkb.josephusproblemlib;

import java.util.Stack;

/**
 * 用栈实现队列
 *
 * @author hkb
 */
public class TestStack {
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        System.out.println("队列 peek=" + myQueue.peek());
        System.out.println("队列 pop=" + myQueue.pop());
        System.out.println("队列 empty=" + myQueue.empty());
    }

    /**
     * 双栈实现队列
     */
    private static class MyQueue {
        Stack<Integer> stack = null;
        Stack<Integer> stack2 = null;

        /**
         * Initialize your data structure here.
         */
        public MyQueue() {
            stack = new Stack<>();
            stack2 = new Stack<>();
        }

        /**
         * Push element x to the back of queue.
         */
        public void push(int x) {
            stack.push(x);
        }

        /**
         * Removes the element from in front of queue and returns that element.
         */
        public int pop() {
            peek();
            return stack2.pop();
        }

        /**
         * Get the front element.
         */
        public int peek() {
            if (stack2.isEmpty()) {
                while (!stack.empty()) {
                    stack2.push(stack.pop());
                }
            }
            return stack2.peek();
        }

        /**
         * Returns whether the queue is empty.
         */
        public boolean empty() {
            return stack.empty() && stack2.empty();
        }
    }
}
